This article delves into retrieving data from other sources. Until now, our apps have primarily remained static. Even the information we showed from GitHub was static information that was hardcoded into our project. So let's use APIs to implement data and make our apps more interactive.
First, we need to understand how data is collected. The typical workflow of a browser is synchronous. Upon receiving HTML, the browser parses the HTML content string and transforms it into a tree object, such as a DOM object or DOM tree. The browser will retrieve remote files (in parallel) and execute them sequentially when it parses the DOM tree and finds them in <\link> and <\script> elements. However, in order to populate data in our app, we will need to request data that isn't currently available from other websites. However, because of the asynchronous nature of external API queries, we'll utilize a package called fetch to make HTTP requests easier.
In order to use fetch, we'll need to install the library in our app we previously created. Let's open up a terminal window again and use npm to install the whatwg-fetch library (an implementation of fetch ). In the same directory where we created our application, let's call:
With the library installed, we can request an off-site server. In order to get access to the fetch library, we'll need to import the package in our script. Let's update the top few lines of our src/App.js file, adding the second line:
With the whatwg-fetch library included in our project, we can make a request using the fetch() api. However, before we can actually start using the fetch() api, we'll need to understand what Promises are and how they work to deal with asynchronous operations. We will learn this in the next article. The complete code for this article is available on my Github.
« Read Previous Article in this Series